﻿using System;
using System.Text;
using System.Runtime.Serialization;
using System.Data.Entity;

namespace Order
{
    [DataContract]
    public class Order
    {
        [DataMember]
        public string OrderID { get; set; }
        [DataMember]
        public Customer Customer { get; set; }
        [DataMember]
        public DateTime OrderTime { get; set; }
        [DataMember]
        public double Total { get; set; }
        [DataMember]
        public Address ShippingAddress { get; set; }
        [DataMember]
        public OrderDetail[] OrderDetails { get; set; }
        public Order(string ID)
        {
            OrderID = ID;
            Customer = new Customer();
            OrderTime = new DateTime();
            ShippingAddress = new Address();
        }
        public override bool Equals(object obj)
        {
            if (obj == null || !(obj is Order o) || o.OrderID == null) return false;
            return o.OrderID.Equals(OrderID);
        }
        public override string ToString()
        {
            if (OrderID == null) throw new NullReferenceException();
            StringBuilder builder = new StringBuilder();
            builder.Append($"Order Id: {OrderID}\nCustomer: {Customer}\nOrder Time: {OrderTime}\n");
            builder.Append($"Total: {Total}\nShipping Address: {ShippingAddress}");
            if (OrderDetails != null)
            {
                foreach (var item in OrderDetails)
                {
                    builder.Append($"\n{item}");
                }
            }
            return builder.ToString();
        }

        public override int GetHashCode()
        {
            return OrderID.GetHashCode();
        }
        public void ComputeTotal()
        {
            foreach(var d in OrderDetails)
            {
                foreach(var o in d.Commodities)
                {
                    Total += o.Price * o.Amount;
                }
            }
        }
    }
}
